#include "DisplayManager.h"
#include <stdio.h>

void DisplayManager::begin() {
  _lcd.init();
  _lcd.backlight();
  pinMode(Pins::LED_RED, OUTPUT);
  pinMode(Pins::LED_GREEN, OUTPUT);
  writeLine1SeedCount(0);
  writeLine2("Initializing...");
}

void DisplayManager::writeLine1SeedCount(uint32_t count) {
  _lcd.setCursor(0, 0);
  char buf[17];
  snprintf(buf, sizeof(buf), "Seeds: %-9lu", (unsigned long)count);
  _lcd.print(buf);
}

void DisplayManager::writeLine2(const char *text) {
  _lcd.setCursor(0, 1);
  char buf[17];
  snprintf(buf, sizeof(buf), "%-16s", text);
  _lcd.print(buf);
}

void DisplayManager::showTransientMessage(const char *msg, unsigned long durationMs) {
  writeLine2(msg);
  _transientActive = true;
  _transientUntilMs = millis() + durationMs;
}

void DisplayManager::update(unsigned long nowMs, uint32_t seedCount, bool conditionsSuitable, bool backlightOn) {
  if (_outOfSeedsShown) return; // frozen on the out-of-seeds screen until refilled

  digitalWrite(Pins::LED_GREEN, conditionsSuitable ? HIGH : LOW);
  digitalWrite(Pins::LED_RED, conditionsSuitable ? LOW : HIGH);

  if (backlightOn != _lastBacklightState) {
    if (backlightOn) _lcd.backlight(); else _lcd.noBacklight();
    _lastBacklightState = backlightOn;
  }

  if (seedCount != _lastShownCount) {
    writeLine1SeedCount(seedCount);
    _lastShownCount = seedCount;
  }

  if (_transientActive && nowMs >= _transientUntilMs) {
    _transientActive = false;
    writeLine2("");
  }
}

void DisplayManager::showOutOfSeeds(uint32_t totalPlanted) {
  _lcd.clear();
  _lcd.setCursor(0, 0);
  _lcd.print("Out of Seeds!");
  char buf[17];
  snprintf(buf, sizeof(buf), "Planted: %-7lu", (unsigned long)totalPlanted);
  _lcd.setCursor(0, 1);
  _lcd.print(buf);
  _outOfSeedsShown = true;
  digitalWrite(Pins::LED_GREEN, LOW);
}

void DisplayManager::updateOutOfSeedsBlink(unsigned long nowMs) {
  if (nowMs - _lastBlinkToggleMs >= 400) {
    _blinkState = !_blinkState;
    digitalWrite(Pins::LED_RED, _blinkState ? HIGH : LOW);
    _lastBlinkToggleMs = nowMs;
  }
}

void DisplayManager::resetAfterRefill() {
  _outOfSeedsShown = false;
  _lastShownCount = 0xFFFFFFFFUL; 
  _lcd.clear();
}
